package com.payroll.taglib.outliner;

import com.payroll.framework.Foundation;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * This is the Outliner class that creates the recursive structure
 * required to build the outliner. The outliner is comprised of the following
 * elements:
 * <li> Table - which is built by the @see com.Payroll.sacwis.outliner.PayrollOutlinerPage tag
 * <li> Filter options - Radio buttons to filter the outliner date built by the
 * @see com.Payroll.sacwis.outliner.AMSOutlinerPage tag
 * <li> 3 Table rows which are the following:
 * <br/> Row 1 - Contains the outliner data.
 * <br/> Row 2 - Second line for displaying extra information for the above row
 * <br/> Row 2 - Place holder row for the next level. This is where the outliner
 * table structure will be inserted making it multi-level by means of recursion.
 * <br/><br/>
 * This object is called from @see com.ams.sacwis.outliner.AMSOutlinerPage tag and
 * @see com.ams.sacwis.outliner.AMSOutlinerElement tag to build the rows. See Syntax
 * as below:<br/>
 * <code>	AMSOutliner m_outliner = new AMSOutliner();
 *	<br/>		pageContext.getOut().print(m_outliner.createRow(m_form).toString());
 * </code>
 */

public class PayrollOutliner {

	String contextPath = null;
	/**
	 * Default constructor.
	 */
	public PayrollOutliner() {

		super();
	}
	/**
	 * To build the outliner an object of type @see com.ams.sacwis.outliner.AMSOutliner object
	 * should be passed to this method. The attributes of the AMSOutliner object determine the
	 * structure of the generated HTML. For example :<br/>
	 * <code>	p_outliner.getIconplus = "provider.bmp";
	 * <br/>	p_outliner.getExpandorlink = "link";
	 * <br/>	p_outliner.getText = "Provider: Day Care";
	 * <br/>	p_outliner.getLink() = "zz11_Provider.do?action=VIEW";
	 * </code><br/>
	 * The HTML generated will have a provider icon and text next to it which states "Provider: Day Care"
	 * which is a link. When the user clicks on the text, an action <code>"zz11_Provider.do?action=VIEW"</code>
	 * will be executed on and the results displayed in a new eSacwis window.
	 *
	 */
	public final StringBuffer createRow(PayrollOutlinerForm p_outliner, String p_contextPath) {
		contextPath = p_contextPath;

		StringBuffer m_return =
			new StringBuffer(
				createDefinitionBegin().toString()
					+ createIcons(
						p_outliner.getCustomcontrol(),
						p_outliner.getIconplus(),
						p_outliner.getIconminus(),
						p_outliner.getExpandorlink(),
						p_outliner.getSubOutlinerDisplay(),
						p_outliner.getNextUrl())
						.toString()
					+ createTextArea(
						p_outliner.getExpandorlink(),
						p_outliner.getText(),
						p_outliner.getLink(),
						p_outliner.getSpecialcase(),
						p_outliner.getRetrievalSearch())
						.toString()
					+ createSecondaryLink(
						p_outliner.getSecondarylink(),
						p_outliner.getSecondarylinktitle(),
						p_outliner.getAdjacentText())
					+ createLaunchDetails(
						p_outliner.getNextUrl(),
						p_outliner.getKey1(),
						p_outliner.getKey2(),
						p_outliner.getKey3(),
						p_outliner.getKey4(),
						p_outliner.getSearchselect(),
						p_outliner.getRetrievalSearch())
						.toString()
					+ createNextLine(p_outliner.getNextLine()).toString()
					+ createNextLevelPlaceholder(p_outliner).toString());
		return m_return;
	}
	private StringBuffer createDefinitionBegin() {
		return new StringBuffer(
			"<TR class='outlinerrow' name='trElem'>");
//				+ " onclick='if (event.srcElement.id.indexOf(\"link\") != -1) {selectRow(this);}'>");
	}

	private StringBuffer createIcons(
		String p_customcontrol,
		String p_iconplus,
		String p_iconminus,
		String p_expandorlink,
		boolean p_expanded,
		String p_link){
		StringBuffer m_return = new StringBuffer(500);

		m_return.append("<TD name='tdElem' class='outlinercustomTD'> ");
		if (!(p_customcontrol == null || p_customcontrol.equals(""))) {
			m_return.append(
				//"<SPAN id='customcontrol' class='outlinercustomcontrol' tabindex='0'>");
			"<SPAN id='customcontrol' class='outlinercustomcontrol' tabindex='0' onkeypress='if(event.keyCode == 32) {firstChild.fireEvent(\"onclick\");}' >");
			m_return.append(p_customcontrol.replace('\"', '\''));
			m_return.append("</SPAN></TD>");
		} else {
			m_return.append("</TD>");
		}

		m_return.append("<TD class='outlinerimageTD'><SPAN name='iconplus'");
		m_return.append(" onfocus=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrowhighlight';\"" );
		m_return.append(" onblur=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrow';\"" );


//  get specific help message, if available
			String m_help = "Open Item";
			try{

// SM04A_MaintainCase.do?action=EDIT
//link looks like above, strip it off to the command and action

			int pathEnd = p_link.indexOf(".do");
			String m_path = p_link.substring(0, pathEnd);

			int actionBegin = p_link.indexOf("action=");
			String m_action = p_link.substring(actionBegin+7);

			//m_help = Foundation.getWidgetHelp(m_path, m_action);
			} catch (Exception e){
			//  do nothing, just won't have the help available for the widget
			m_help = "Open Item";
			}



		if (p_expandorlink.equals("expand") || p_expandorlink.equals("both")) {
			m_return.append(" title='" + m_help + "' onclick='expand()'" +
							"onkeydown='if (event.keyCode == 13) expand();' class='outlinerimage'");
		} else {
			m_return.append(" class='outlinerimageonly' ");
		}
		if(p_iconplus.equals("case_alert.bmp"))
		{
		m_return.append(
		" style=" + (p_expanded ? "\"display:none\"": "\"display:inline\"") + "tabindex='0'>"
		+ " <IMG alt='alert icon'  name = 'opengif' "
		+ " src=\""
		+ (p_iconplus == null
		|| p_iconplus.equals("") ? contextPath + "/images/blank.bmp" : contextPath + "/images/" + p_iconplus)
		+ "\" border=\"0\"/></SPAN>");
		}
		else
		{
			m_return.append(" style=" + (p_expanded ? "\"display:none\"": "\"display:inline\"") + "tabindex='0'>");
			if (p_expandorlink.equals("expand") || p_expandorlink.equals("both")) {
				m_return.append(" <IMG alt='Expand'");
			} else {
				m_return.append(" <IMG alt='Not Expandable'");
			}
			m_return.append(
			" name = 'opengif' src=\""
			+ (p_iconplus == null
			|| p_iconplus.equals("") ? contextPath + "/images/blank.bmp" : contextPath + "/images/" + p_iconplus)
			+ "\" border=\"0\"/></SPAN>");
		}


		m_return.append("<SPAN name='iconminus'");
		m_return.append(" onfocus=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrowhighlight';\"" );
		m_return.append(" onblur=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrow';\"" );
		if (p_expandorlink.equals("expand") || p_expandorlink.equals("both")) {
			m_return.append(" title='Close Item'  onclick='collapse()' " +
							"onkeydown='if (event.keyCode == 13) collapse();'  class='outlinerimage'");
		} else {
			m_return.append(" class='outlinerimageonly' ");
		}
		if(p_iconminus.equals("case_alert.bmp"))
		{
		m_return.append(
			" style = " + (p_expanded ? "\"display:inline\"": "\"display:none\"") + " tabindex='0'>"
				+ " <IMG name='closegif' alt=\'Alert Collapse\' "
				+ " src=\""
				+ (p_iconminus == null
					|| p_iconminus.equals("")
						? contextPath + "/images/blank.bmp"
						: contextPath + "/images/" + p_iconminus)
				+ "\" border=\"0\"/></SPAN></TD>");
		} else {
			m_return.append(
					" style = " + (p_expanded ? "\"display:inline\"": "\"display:none\"") + " tabindex='0'>"
						+ " <IMG name='closegif' alt=\'Collapse\' "
						+ " src=\""
						+ (p_iconminus == null
							|| p_iconminus.equals("")
								? contextPath + "/images/blank.bmp"
								: contextPath + "/images/" + p_iconminus)
						+ "\" border=\"0\"/></SPAN></TD>");
		}
		return m_return;
	}

	private StringBuffer createTextArea(
		String p_expandorlink,
		String p_text,
		String p_link,
		boolean p_special,
		String retrievalSearch) {
		StringBuffer m_return = new StringBuffer(200);

		if(retrievalSearch.equals("Y")){
			if (p_expandorlink.equals("expand") || p_expandorlink.equals("none")){
				//nothing
			} else if (p_expandorlink.equals("both"))
			{
				p_expandorlink = "expand";
			} else if (p_expandorlink.equals("link")){
				p_expandorlink = "none";
			} else {
				p_expandorlink = "none";
			}
		}

		if (p_expandorlink.equals("expand") || p_expandorlink.equals("none")) {
			m_return.append(
				"<TD class='outlinerrow'><SPAN name='link' class='"
					+ (p_special == true ? "outlinertextspecial" : "outlinertext")
					+ "' >"
					+ (p_text == null || p_text.equals("") ? "None" : p_text)
					+ "</SPAN>");
		} else {
			String m_help = "";
			try{

// SM04A_MaintainCase.do?action=EDIT&CASE_ID_CASE=
//link looks like above, strip it off to the command and action

			int pathEnd = p_link.indexOf(".do");
			String m_path = p_link.substring(0, pathEnd);

			int actionBegin = p_link.indexOf("action=");
			int actionEnd = p_link.indexOf("&", actionBegin);
			String m_action = p_link.substring(actionBegin+7, actionEnd);

			//m_help = Foundation.getWidgetHelp(m_path, m_action);
			} catch (Exception e){
			//  do nothing, just won't have the help available for the widget
			m_help = "";
			}
			m_return.append(
				(m_help == null
					|| m_help.equals("") ? "<TD class='outlinerrow'> <SPAN name='link' id='link' tabindex='0' onclick='launch(\"" : "<TD class='outlinerrow'><SPAN name='link' tabindex='0' id='link' title=\"" + m_help + "\" onclick='launch(\"")
					+ (p_link == null
						|| p_link.equals("") ? "../common/FatalApplicationError.jsp" : contextPath + p_link)
					+ "\")'"
					+ " onfocus=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrowhighlight'; " + (m_help.equals("") ? "window.status = ''" : "window.status='" + m_help + "'") + "\""
					+ " onblur=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrow';window.status='';\""
					+ " onkeydown='if (event.keyCode == 13) fireEvent(\"onclick\");'"
					+ " class='"
					+ (p_special == true ? "outlinerspeciallink" : "outlinerlink")
					+ "' onmouseout=\"this.className='"
					+ (p_special == true ? "outlinerspeciallink" : "outlinerlink")
					+ "'\" onmouseover=\"this.className='outlinerlinkhover'\" >"
					+ (p_text == null || p_text.equals("") ? "None" : p_text)
					+ "</SPAN>");
		}
		return m_return;

	}

	private StringBuffer createLaunchDetails(
		String p_nextUrl,
		String p_key1,
		String p_key2,
		String p_key3,
		String p_key4,
		String searchselect,
		String retrievalSearch) {
		return new StringBuffer(
			"<TD><SPAN id=\"nextUrl\" style=\"display: none\">"
				+ (p_nextUrl == null
					|| p_nextUrl.equals("") ? contextPath + "/common/FatalApplicationError.jsp" : contextPath + p_nextUrl)
				+ "</SPAN> <SPAN id=\"key1\" style=\"display: none\">"
				+ p_key1
				+ "</SPAN> <SPAN id=\"key2\" style=\"display: none\">"
				+ p_key2
				+ "</SPAN> <SPAN id=\"key3\" style=\"display: none\">"
				+ p_key3
				+ "</SPAN> <SPAN id=\"key4\" style=\"display: none\">"
				+ p_key4
				+ "</SPAN> <SPAN id=\"searchselect\" style=\"display: none\">"
				+ searchselect
				+ "</SPAN> <SPAN id=\"retrievalSearch\" style=\"display: none\">"
				+ retrievalSearch
				+ "</SPAN>"
				+ "</TD></TR>");
	}

	private StringBuffer createSecondaryLink(
		String p_secondarylink,
		String p_secondarylinktitle,
		String p_adjacentText) {

		if ( (p_secondarylink == null || p_secondarylink.equals("")) && (p_adjacentText == null || p_adjacentText.equals(""))){
			return new StringBuffer("</TD>");
		}

		StringBuffer m_return = new StringBuffer(500);

		if ((p_secondarylink != null && !p_secondarylink.equals(""))){
			m_return.append(
				"<SPAN name='secondaryLink' id='secondarylink' tabindex='0' onclick=\"launch('"
					+ contextPath + p_secondarylink
					+ "');\" class='outlinersecondarylink' onmouseout=\"this.className='outlinersecondarylink'\" onmouseover=\"this.className='outlinersecondarylinkhover'\" title='"
						+ p_secondarylinktitle + "'"
						+ " onkeydown='if (event.keyCode == 13) fireEvent(\"onclick\");'"
						+ " onfocus=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrowhighlight';window.status='" + p_secondarylinktitle + "'" + "\""
						+ " onblur=\"parentElement.parentElement.firstChild.nextSibling.nextSibling.className='outlinerrow';window.status='';\"/>Actions");
			m_return.append("</SPAN>");
		}
		if ((p_adjacentText != null && !p_adjacentText.equals(""))){
			m_return.append(createAdjacentText(p_adjacentText).toString());
		}
		m_return.append("</TD>");
		return m_return;
	}

	private StringBuffer createAdjacentText (String p_adjacentText){
		StringBuffer m_buffer=new StringBuffer("<SPAN class='outlinerAjdText'>");
		m_buffer.append(p_adjacentText);
		m_buffer.append("</SPAN>");
		return m_buffer;
	}

	private StringBuffer createNextLine(String p_nextLine) {
		StringBuffer m_return = new StringBuffer(500);

		m_return.append("<TR name='nextLine' ");
		if (!(p_nextLine == null || p_nextLine.equals(""))) {
			m_return.append(
				" class = 'outlinernextlinevisible' style='display:inline;'><TD/><TD/><TD> "
					+ p_nextLine
					+ "</TD>");
		} else {
			m_return.append(
				" class='outlinernextlinehidden' style='display:none;'><TD/><TD/><TD/>");
		}
		m_return.append("</TR>");
		return m_return;
	}

	private StringBuffer createNextLevelPlaceholder(PayrollOutlinerForm p_outliner) {
		StringBuffer m_sb = new StringBuffer();
		int i, j;
		ArrayList m_subOutliner = null;
		m_sb.append(
			"<TR name='nTr' style='display:inline;width:100%'>"
				+ "<TD/><TD/><TD nowrap name='ntdElem' style='display:inline;'>"
				+ "<DIV id='nextDiv' ");
		// This makes the outliner recursive to any levels. If the application decides to show
		// multiple levels go for it! Outliner can handle it. Not sure if the application developer
		// will be able to go more than one level
		if (p_outliner.getSubOutlinerDisplay()) {
			m_subOutliner = p_outliner.getSubOutliner();
			if (m_subOutliner != null) {
				m_sb.append("style='display:inline;width:100%;'");
				m_sb.append("<DIV id=\"outlinerdiv\">");
				m_sb.append(
					"<TABLE class='outlinertable' name=\"outlinertable\" cellpadding=\"0\" cellspacing=\"0\"><TBODY>");

				PayrollOutliner m_outliner = new PayrollOutliner();
				for (i = 0; i < m_subOutliner.size(); i++) {
					m_sb.append(
						m_outliner.createRow((PayrollOutlinerForm) m_subOutliner.get(i), contextPath));
				}
				m_sb.append("</TBODY></TABLE></DIV>");
			} else {
				m_sb.append("style='display:inline;width:100%'>No rows found");

			}
		} else {
			m_sb.append("style='display:none;width:100%'>");
		}
		m_sb.append("</DIV>" + "</TD>" + "</TR>");
		return m_sb;
	}
}